package com.jzbooks.handler;

import com.jzbooks.enums.ResultCodeEnum;
import com.jzbooks.exception.BusinessException;
import com.jzbooks.result.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mingPeng
 * @date 2021/4/19 19:29
 * @Description :
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
            * 如果没有使用 @ResponseStatus 来注明状态，需要通过 throw new 来抛出异常
     * 处理通用自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ErrorResult handleBusinessException(BusinessException e, HttpServletRequest request) {
//        log.error("handleBusinessException start, uri:{}, exception:{}, caused by: {}"
//                , request.getRequestURI()
//                , e.getClass()
//                , e.getMessage() + e.getData());
        return ErrorResult.failure(e);
    }

    /**
     * 处理运行时系统异常（反500错误码）
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public ErrorResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("handleRuntimeException start, uri:{}, caused by: ", request.getRequestURI(), e);
        return ErrorResult.failure(ResultCodeEnum.SYSTEM_INNER_ERROR, e, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
